$(document).ready(function () {
    let table = $('#productsTable').DataTable({
        "fnPreDrawCallback": function (oSettings) {
            var processing_div = $('#productsTable_processing');
            processing_div.removeClass("card");
            processing_div.addClass("align-middle");

        },
        "ajax": {
            url: "/api/products/",
            type: "GET",
        },
        "ordering": false,
        "serverSide": true,
        "lengthChange": false,
        "searching": true,
        "bProcessing": true,
        "dom": "<'row'<'col-sm-12 col-md-12'f>>" +
            "<'row'<'col-sm-12'tr>>" +
            "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
        "language": {
            "sSearch": "",
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "没有数据！",
            "sEmptyTable": "当前未查询到产品信息",
            "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
            "sInfoEmpty": "显示0到0条记录",
            "sInfoFiltered": "数据表中共有 _MAX_ 条记录",
            "sProcessing": '<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>\n' +
                '<span class="sr-only">Loading...</span>',
            "sLoadingRecords": '',
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"

            }
        },
        "columns": [
            {
                data: 'fields.name',
                sDefaultContent: "-"
            },
            {
                data: 'fields.item_num',
                sDefaultContent: "-"
            },
            {
                data: 'fields.uni_prot',
                sDefaultContent: "-"
            },
            {
                data: 'fields.antibody_type',
                sDefaultContent: "-"
            },
            {
                data: 'fields.molecular_weight',
                sDefaultContent: "-"
            },
            {
                data: 'fields.positive_part',
                sDefaultContent: "-"
            },
            {
                data: 'fields.pretreatment',
                sDefaultContent: "-",
            },
            {
                data: 'fields.clone_num',
                sDefaultContent: "-"
            },
            {
                data: 'fields.storage_validity_period',
                sDefaultContent: "-",
                visible: false
            },
            {
                data: 'fields.description',
                sDefaultContent: "-",
                width: "12%",
                visible: false
            },
            {
                data: 'fields.remarks',
                sDefaultContent: "-",
                width: "12%",
                visible: false
            },
            {
                data: 'fields.experimental_program',
                sDefaultContent: "-",
                width: "12%",
                visible: false
            },
            {
                data: {
                    fields: 'fields',
                },
                sDefaultContent: "-",
                visible: false,
                "render": function (data) {
                    let product_images_html = '';
                    let product_images_list = data['fields']['product_images_list'];
                    if (product_images_list !== '') {
                        let tmp_product_images_list = JSON.parse(product_images_list.replace(/\'/g,'\"'));
                        if (tmp_product_images_list.length > 3) {
                            tmp_product_images_list = tmp_product_images_list.slice(0,3);
                        }
                        for (let i=0;i<tmp_product_images_list.length;i++) {
                            product_images_html = product_images_html + '<a href="'+tmp_product_images_list[0]+'" target="_blank">图片'+i+'</a><br>'
                        }
                        return product_images_html
                    } else {
                        return "未上传"
                    }
                }
            },
            {
                data: {
                    fields: 'fields',
                },
                sDefaultContent: "-",
                visible: false,
                "render": function (data) {
                    let product_guide_book = data['fields']['product_guide_book'];
                    if (product_guide_book === "") {
                        return "未上传"
                    } else {
                        return '<a href="'+product_guide_book+'" target="_blank">查看说明书</a>'
                    }
                }
            },
            {
                data: {
                    fields: 'fields',
                },
                width: "8%",
                "render": function (data) {
                    let product_id = data['pk'],

                        product_name = Base64.encode(data['fields']['name']),
                        item_num = Base64.encode(data['fields']['item_num']),
                        uni_prot = Base64.encode(data['fields']['uni_prot']),
                        antibody_type = Base64.encode(data['fields']['antibody_type']),
                        molecular_weight = Base64.encode(data['fields']['molecular_weight']),
                        positive_part = Base64.encode(data['fields']['positive_part']),
                        pretreatment = Base64.encode(data['fields']['pretreatment']),
                        clone_num = Base64.encode(data['fields']['clone_num']),
                        storage_validity_period = Base64.encode(data['fields']['storage_validity_period']),
                        description = Base64.encode(data['fields']['description']),
                        experimental_program = Base64.encode(data['fields']['experimental_program']),
                        remarks = Base64.encode(data['fields']['remarks']);

                    action = '<a class="dropdown-item" href="javascript:void(0)" data-toggle="modal" data-target="#editProduct" onclick="edit_product_modal(\'' + product_id + '\',\'' + product_name + '\',\'' + item_num + '\',\'' + uni_prot + '\',\'' + antibody_type + '\',\'' + molecular_weight + '\',\'' + positive_part + '\',\'' + pretreatment + '\',\'' + clone_num + '\',\'' + storage_validity_period + '\',\'' + description + '\',\'' + experimental_program + '\',\'' + remarks + '\')">编辑</a>\n' +
                        '<a class="dropdown-item" href="javascript:void(0)" data-toggle="modal" data-target="#deleteProduct" onclick="delete_product_modal(\'' + product_id + '\',\'' + product_name + '\',\'' + item_num + '\')">删除</a>\n' +
                        '<a class="dropdown-item" href="javascript:void(0)" data-toggle="modal" data-target="#uploadImage" onclick="uploadImageModal(\'' + product_id + '\')">上传图片</a>\n' +
                        '<a class="dropdown-item" href="javascript:void(0)" data-toggle="modal" data-target="#uploadPdf" onclick="uploadPdfModal(\'' + product_id + '\')">上传产品说明书</a>\n' +
                        '<a class="dropdown-item" href="javascript:void(0)" data-toggle="modal" data-target="#addOrder" onclick="addOrderModal(\'' + item_num + '\')">添加订货信息</a>\n';
                    return '<a href="javascript:void(0);"  id="ctl-dropdownMenuLink" data-toggle="dropdown" data-flip="false" aria-haspopup="true" aria-expanded="true">更多</a>\n' +
                        '<div class="dropdown-menu" data-flip="false" aria-labelledby="ctl-dropdownMenuLink">\n' +
                        action +
                        '</div>'
                }
            }
        ]
    });
    $('.dataTables_filter').attr("hidden", "hidden");

});

function addOrderModal(item_num) {
    $('#add_product_item_num').val(Base64.decode(item_num));
    $('#add_product_sub_item_num').val('');
    $('#add_order_flavor').val('');
    $('#add_order_unit').val('');
    $('#add_product_type').val('');
}

function add_order() {
    let check_valid,
        selector_Id;
    check_valid = check_form("addOrder");
    if (check_valid) {
        selector_Id = check_valid.id;
        $('#' + selector_Id + '').css('border', 'solid 2px #ff0000');
        setTimeout(remove_css, 1000);
    } else {
        let add_product_item_num = $('#add_product_item_num').val(),
            add_product_sub_item_num = $('#add_product_sub_item_num').val(),
            add_order_flavor = $('#add_order_flavor').val(),
            add_order_unit = $('#add_order_unit').val(),
            add_product_type = $('#add_product_type').val();
        $.ajax({
            url: "/api/orders/",
            async: true,
            type: "POST",
            data: JSON.stringify({
                product_item_num: add_product_item_num,
                sub_item_num: add_product_sub_item_num,
                flavor: add_order_flavor,
                unit: add_order_unit,
                product_type: add_product_type
            }),
            contentType: "application/json; charset=utf-8",
            success: function (data) {   // success callback function
                $('#page-heading').before('<div class="alert alert-success alert-dismissible" style="z-index: 9999;position: absolute;left: 45%">\n' +
                    '<button type="button" class="close" data-dismiss="alert">&times;</button><span>订货信息添加成功！</span>\n' +
                    '    </div>')
                setTimeout('$(".alert").alert("close")',3000);
                $("#addOrder").modal('hide');
                window.location.href = "/console/orders/";
            },
            error: function (result) {
                $("#addOrder").modal('hide');
                if (result['status'] === 403) {
                    alert("403！你没有权限操作！")
                } else {
                    alert(result['status'] + "," + result['statusText'])
                }
            },
            // dataType: "json" //返回值类型
        })
    }


}

function add_product_modal() {
    $('#add_product_name').val("");
    $('#add_item_num').val("");
    $('#add_uni_prot').val("");
    $('#add_antibody_type').val("");
    $('#add_molecular_weight').val("");
    $('#add_positive_part').val("");
    $('#add_pretreatment').val("");
    $('#add_clone_num').val("");
    $('#add_storage_validity_period').val("");
    $('#add_description').val("");
    $('#add_experimental_program').val("");
    $('#add_remarks').val("");
}

function choose_table_fields(obj) {
    let checked = $(obj).is(':checked');
    let index = $(obj).parent().parent().index();
    let table = $('#productsTable').DataTable();
    table.column(index).visible(checked);
}

function uploadImageModal(product_id) {
    $('#product_id_span').text(product_id);
    $('#uploadImg').val('');
    window.filesList = [];
}

function uploadFileModal() {
    $('#input_upload_file').val('');
    $('#input_upload_file').next(".custom-file-label").attr('data-content', "选择文件");
    $('#input_upload_file').next(".custom-file-label").text("选择文件");
}

function uploadPdfModal(product_id) {
    $('#usage_product_id_span').text(product_id);
    $('#input_upload_pdf').val('');
    $('#input_upload_pdf').next(".custom-file-label").attr('data-content', "选择文件");
    $('#input_upload_pdf').next(".custom-file-label").text("选择文件");
}

function upload_imgs() {
    let form_data = new FormData();
    let product_id = $('#product_id_span').text();
    if (window.filesList.length === 0 ) {
        $('#page-heading').before('<div class="alert alert-success alert-dismissible" style="z-index: 9999;position: absolute;left: 45%">\n' +
            '<button type="button" class="close" data-dismiss="alert">&times;</button><span>上传图片成功！</span>\n' +
            '    </div>')
        setTimeout('$(".alert").alert("close")',3000);
        $("#uploadImage").modal('hide');
    } else {
        for (let i=0;i< window.filesList.length;i++) {
            form_data.append('file', window.filesList[i]);
        }
        form_data.append('product_id', product_id)
        $.ajax({
            url: '/api/image_processor/upload/',
            type: 'POST',
            data: form_data,
            processData: false,  // tell jquery not to process the data
            contentType: false, // tell jquery not to set contentType
            success: function (callback) {
                $('#page-heading').before('<div class="alert alert-success alert-dismissible" style="z-index: 9999;position: absolute;left: 45%">\n' +
                    '<button type="button" class="close" data-dismiss="alert">&times;</button><span>上传图片成功</span>\n' +
                    '    </div>')
                setTimeout('$(".alert").alert("close")',3000);
                $("#uploadImage").modal('hide');
                let table = $('#productsTable').DataTable();
                let timesRun = 0;
                let start_interval = setInterval(function () {
                    timesRun += 1;
                    if (timesRun === 1) {
                        clearInterval(start_interval);
                    }
                    table.ajax.reload(null, false);
                }, 2000);
            },
            error: function (result) {
                if (result['status'] === 403){
                    alert("403！你没有权限操作该实例！")
                } else {
                    alert("上传图片失败，"+result['status'] + "," + result['statusText'])
                }
                $("#uploadImage").modal('hide');
            }
        });
    }
}

function upload_pdf() {
    let form_data = new FormData();
    let product_id = $('#usage_product_id_span').text();
    let file_info = $('#input_upload_pdf')[0].files[0];
    if (file_info === undefined) {
        alert("请先选择文件！！！")
    } else {
        form_data.append('file', file_info);
        form_data.append('product_id',product_id);
        $.ajax({
            url: '/api/data_processor/uploadPdf/',
            type: 'POST',
            data: form_data,
            processData: false,  // tell jquery not to process the data
            contentType: false, // tell jquery not to set contentType
            success: function (callback) {
                $('#page-heading').before('<div class="alert alert-success alert-dismissible" style="z-index: 9999;position: absolute;left: 45%">\n' +
                        '<button type="button" class="close" data-dismiss="alert">&times;</button><span>上传产品说明书成功!</span>\n' +
                        '    </div>')
                    setTimeout('$(".alert").alert("close")',3000);
                $("#uploadPdf").modal('hide');
                let table = $('#productsTable').DataTable();
                let timesRun = 0;
                let start_interval = setInterval(function () {
                    timesRun += 1;
                    if (timesRun === 1) {
                        clearInterval(start_interval);
                    }
                    table.ajax.reload(null, false);
                }, 2000);
            },
            error: function (result) {
                $("#uploadPdf").modal('hide');
                alert(result['responseJSON']['msg']);
            },
        });
    }

}

function edit_product_modal(product_id, product_name, item_num, uni_prot, antibody_type, molecular_weight, positive_part, pretreatment, clone_num, storage_validity_period, description, experimental_program, remarks) {
    $('#edit_product_id').val(product_id);
    $('#edit_product_name').val(Base64.decode(product_name));
    $('#edit_item_num').val(Base64.decode(item_num));
    $('#edit_uni_prot').val(Base64.decode(uni_prot));
    $('#edit_antibody_type').val(Base64.decode(antibody_type));
    $('#edit_molecular_weight').val(Base64.decode(molecular_weight));
    $('#edit_positive_part').val(Base64.decode(positive_part));
    $('#edit_pretreatment').val(Base64.decode(pretreatment));
    $('#edit_clone_num').val(Base64.decode(clone_num));
    $('#edit_storage_validity_period').val(Base64.decode(storage_validity_period));
    $('#edit_description').val(Base64.decode(description));
    $('#edit_experimental_program').val(Base64.decode(experimental_program));
    $('#edit_remarks').val(Base64.decode(remarks));
}

function delete_product_modal(product_id, product_name, item_num) {
    $('#delete_product_id').text(product_id);
    $('#delete_product_name').text(Base64.decode(product_name));
    $('#delete_item_num').text(Base64.decode(item_num));
}

function add_product() {
    let check_valid,
        selector_Id;
    check_valid = check_form("addProduct")
    if (check_valid) {
        selector_Id = check_valid.id;
        $('#' + selector_Id + '').css('border', 'solid 2px #ff0000');
        setTimeout(remove_css, 1000);
    } else {
        const product_name = $('#add_product_name').val(),
        item_num = $('#add_item_num').val(),
        uni_prot = $('#add_uni_prot').val(),
        antibody_type = $('#add_antibody_type').val(),
        molecular_weight = $('#add_molecular_weight').val(),
        positive_part = $('#add_positive_part').val(),
        pretreatment = $('#add_pretreatment').val(),
        clone_num = $('#add_clone_num').val(),
        storage_validity_period = $('#add_storage_validity_period').val(),
        description = $('#add_description').val(),
        experimental_program = $('#add_experimental_program').val(),
        remarks = $('#add_remarks').val();
        $.ajax({
                url: "/api/products/",
                async: true,
                type: "POST",
                data: JSON.stringify({
                    product_name: product_name,
                    item_num: item_num,
                    uni_prot: uni_prot,
                    antibody_type: antibody_type,
                    molecular_weight: molecular_weight,
                    positive_part: positive_part,
                    pretreatment: pretreatment,
                    clone_num: clone_num,
                    storage_validity_period: storage_validity_period,
                    description: description,
                    experimental_program: experimental_program,
                    remarks: remarks
                }),
                contentType: "application/json; charset=utf-8",
                success: function (data) {   // success callback function
                    $('#page-heading').before('<div class="alert alert-success alert-dismissible" style="z-index: 9999;position: absolute;left: 45%">\n' +
                        '<button type="button" class="close" data-dismiss="alert">&times;</button><span>产品添加成功！</span>\n' +
                        '    </div>')
                    setTimeout('$(".alert").alert("close")',3000);
                    $("#addProduct").modal('hide');
                    let table = $('#productsTable').DataTable();
                    let timesRun = 0;
                    let start_interval = setInterval(function () {
                        timesRun += 1;
                        if (timesRun === 1) {
                            clearInterval(start_interval);
                        }
                        table.ajax.reload(null, false);
                    }, 2000);
                },
                error: function (result) {
                    $("#addProduct").modal('hide');
                    if (result['status'] === 403) {
                        alert("403！你没有权限操作！")
                    } else {
                        alert(result['status'] + "," + result['statusText'])
                    }
                },
                // dataType: "json" //返回值类型
            }
        );
    }
}

function edit_product() {
    let check_valid,
        selector_Id;
    check_valid = check_form("editProduct")
    if (check_valid) {
        selector_Id = check_valid.id;
        $('#' + selector_Id + '').css('border', 'solid 2px #ff0000');
        setTimeout(remove_css, 1000);
    } else {
        let product_id = $('#edit_product_id').val(),
        product_name = $('#edit_product_name').val(),
        item_num = $('#edit_item_num').val(),
        uni_prot = $('#edit_uni_prot').val(),
        antibody_type = $('#edit_antibody_type').val(),
        molecular_weight = $('#edit_molecular_weight').val(),
        positive_part = $('#edit_positive_part').val(),
        pretreatment = $('#edit_pretreatment').val(),
        clone_num = $('#edit_clone_num').val(),
        storage_validity_period = $('#edit_storage_validity_period').val(),
        description = $('#edit_description').val(),
        experimental_program = $('#edit_experimental_program').val(),
        remarks = $('#edit_remarks').val();
        $.ajax({
                url: "/api/products/" + product_id + "/",
                async: true,
                type: "PUT",
                data: JSON.stringify({
                    product_name: product_name,
                    item_num: item_num,
                    uni_prot: uni_prot,
                    antibody_type: antibody_type,
                    molecular_weight: molecular_weight,
                    positive_part: positive_part,
                    pretreatment: pretreatment,
                    clone_num: clone_num,
                    storage_validity_period: storage_validity_period,
                    description: description,
                    experimental_program: experimental_program,
                    remarks: remarks
                }),
                contentType: "application/json; charset=utf-8",
                success: function (data) {   // success callback function
                    $('#page-heading').before('<div class="alert alert-success alert-dismissible" style="z-index: 9999;position: absolute;left: 45%">\n' +
                        '<button type="button" class="close" data-dismiss="alert">&times;</button><span>产品修改成功！</span>\n' +
                        '    </div>')
                    setTimeout('$(".alert").alert("close")',3000);
                    $("#editProduct").modal('hide');
                    let table = $('#productsTable').DataTable();
                    let timesRun = 0;
                    let start_interval = setInterval(function () {
                        timesRun += 1;
                        if (timesRun === 1) {
                            clearInterval(start_interval);
                        }
                        table.ajax.reload(null, false);
                    }, 2000);
                },
                error: function (result) {
                    $("#editProduct").modal('hide');
                    if (result['status'] === 403) {
                        alert("403！你没有权限操作！")
                    } else {
                        alert(result['status'] + "," + result['statusText'])
                    }
                },
                // dataType: "json" //返回值类型
            }
        );
    }

}

function delete_product() {
    const product_id = $('#delete_product_id').text();
    $.ajax({
            url: "/api/products/" + product_id + "/",
            async: true,
            type: "DELETE",
            contentType: "application/json; charset=utf-8",
            success: function (data) {   // success callback function
                $('#page-heading').before('<div class="alert alert-success alert-dismissible" style="z-index: 9999;position: absolute;left: 45%">\n' +
                    '<button type="button" class="close" data-dismiss="alert">&times;</button><span>产品删除成功！</span>\n' +
                    '    </div>')
                setTimeout('$(".alert").alert("close")',3000);
                $("#deleteProduct").modal('hide');
                let table = $('#productsTable').DataTable();
                let timesRun = 0;
                let start_interval = setInterval(function () {
                    timesRun += 1;
                    if (timesRun === 1) {
                        clearInterval(start_interval);
                    }
                    window.location.reload();
                }, 2000);
            },
            error: function (result) {
                $("#deleteProduct").modal('hide');
                if (result['status'] === 403) {
                    alert("403！你没有权限操作！")
                } else {
                    alert(result['status'] + "," + result['statusText'])
                }
            },
            // dataType: "json" //返回值类型
        }
    );
}

function upload_file(type) {
    let form_data = new FormData();
    let file_info = $('#input_upload_file')[0].files[0];
    form_data.append('file', file_info);
    form_data.append('type',type)
    $.ajax({
        url: '/api/data_processor/upload/',
        type: 'POST',
        data: form_data,
        processData: false,  // tell jquery not to process the data
        contentType: false, // tell jquery not to set contentType
        success: function (callback) {
            $('#page-heading').before('<div class="alert alert-success alert-dismissible" style="z-index: 9999;position: absolute;left: 45%">\n' +
                    '<button type="button" class="close" data-dismiss="alert">&times;</button><span>产品导入成功!</span>\n' +
                    '    </div>')
                setTimeout('$(".alert").alert("close")',3000);
            $("#uploadFile").modal('hide');
            let table = $('#productsTable').DataTable();
            let timesRun = 0;
            let start_interval = setInterval(function () {
                timesRun += 1;
                if (timesRun === 1) {
                    clearInterval(start_interval);
                }
                table.ajax.reload(null, false);
            }, 2000);
        },
        error: function (result) {
            $("#uploadFile").modal('hide');
            alert(result['responseJSON']['msg']);
        },
    });
}

function download_file(action) {
    let httpMethod = 'get';
    let url = "/api/data_processor/download?action="+action;
    $.fileDownload(url, {
        httpMethod: httpMethod,
        // 因为这个插件貌似只支持URL参数,所以要用jquery param将js对象转成URL参数
        prepareCallback: function (url) {
            console.log("正在导出...");
        },
        //要想成功回调失败和成功方法，要在响应首部加 response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        successCallback: function (url) {
            console.log("导出成功");
        },
        failCallback: function (html, url) {
            console.log("导出失败");
        }
    })
}

function refresh_table() {
    let table = $('#productsTable').DataTable();
    table.ajax.reload();
}

function check_form(id) {
    /**判断是否有选项为空
     * **/
    let result = '',
        element = $('#'+id+'');

    element.find('[required]').each(
        function () {
            let fieldElement = $(this);
            //如果为null则设置为''
            let value = fieldElement.val() || '';
            // console.log(this);
            if (value) {
                if (Array.isArray(value)) {
                    if (value.length === 0 ) {
                       value = false
                    }
                } else {
                    value = value.trim();
                }
            }

            if (!value) {
                result = this;
                return result;
            }
        }
    );
    return result;
}

function remove_css() {
    $('[required]').css('border', '1px solid #d1d3e2')
}

function filter_products() {
    const filter_condition = $('#filter_condition').val(),
        filter_content = "query" + "=" + filter_condition,
        table = $('#productsTable').DataTable();
    table.search(filter_content).draw();
}

$(document).keyup(function (event) {
    if (event.keyCode === 13) {
        filter_products();
    }
});
